package com.example.cpl.gjc;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class clear_fault extends AppCompatActivity {
    //声明控件
    private VideoView mVideoView;
    private static final String TAG = "TAG";
    private static final String IP_HEAD = "192.168.31.";
    private int wi=0,bb=0;
    private Button btn_cx,btn_Back;
    private EditText et_id;
    static Handler mHandler;
    static ExecutorService mThreadPool;
    static Socket socket;  // Socket变量
    static OutputStream outputStream;
    //    public boolean a;
//        String rec;        // 接收服务器发送过来的消息
    InputStream is;         // 输入流对象
    InputStreamReader isr ; // 输入流读取器对象
    static BufferedReader br ;     // 输入流读取器对象
    String ab;
    ProgressDialog m_pDialog;
    private TextView fault_login_name,fault_online_num;
    public void initWidght(){
        btn_Back=(Button)findViewById(R.id.fault_back);
        btn_cx=(Button)findViewById(R.id.fault_btn_cx);
       // btn_qk=(Button)findViewById(R.id.fault_btn_qk);
        et_id=(EditText) findViewById(R.id.fault_et_id);
        fault_login_name=(TextView)findViewById(R.id.fault_login_name);
        fault_online_num=(TextView)findViewById(R.id.fault_online_num);
        fault_login_name.setText(teach_center.who);
        fault_online_num.setText(""+device_manage.dev_num+"");
    }

    public void ProgressShow() {
        m_pDialog = new ProgressDialog(clear_fault.this);// 创建ProgressDialog对象
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置进度条风格，风格为长形
        m_pDialog.setTitle("提示"); // 设置ProgressDialog 标题
        m_pDialog.setMessage("正在连接 请等待...");  // 设置ProgressDialog 提示信息
        m_pDialog.setIcon(R.drawable.icon); // 设置ProgressDialog 标题图标
//        m_pDialog.setMax(0);// 设置进度条最大值
        m_pDialog.setIndeterminate(true);  // 设置ProgressDialog 的进度条是否不明确
        m_pDialog.setCancelable(false); // 设置ProgressDialog 是否可以按退回按键取消
        m_pDialog.show(); // 让ProgressDialog显示
    }
    public void Connect_Tcp(final String ip, final int port) {
        Log.d(TAG,"TCP连接中...");
        try {

            socket = new Socket(""+ip+"",port);

            Log.d(TAG,"TCP连接成功");
            is = socket.getInputStream();             // 步骤1：创建输入流对象InputStream
            isr = new InputStreamReader(is);          // 步骤2：创建输入流读取器对象 并传入输入流对象
            br = new BufferedReader(isr);             // 该对象作用：发送数据
            outputStream = socket.getOutputStream();  // 步骤2：写入需要发送的数据到输出流对象中
            outputStream.write(("aaaaaaaaaa\r\n").getBytes("utf-8"));    // 数据的结尾加上换行符才可让服务器端的readline()停止阻塞
            Log.d(TAG,"——查询成绩");
//               outputStream.write(("start" +wi+ "\n").getBytes("utf-8"));    //可以发送int类型的
            // 步骤3：发送数据到服务端
            outputStream.flush();
            Log.d(TAG,"TCP数据发送成功");
            Toast.makeText(getApplicationContext(), "清除故障成功！", Toast.LENGTH_SHORT)
                    .show();//阴影提示框
            bb=1;

            Message msg=new Message();
            msg.what=0x03; //这里判断是否连接成功
            mHandler.sendMessage(msg);

            String rec = null;        // 接收服务器发送过来的消息
            while ((rec = br.readLine()) != null)
            {
                Log.d(TAG,"TCP接收数据中。。。。。");
                msg = new Message();
                msg.what=0x01;
                msg.obj=rec;

                mHandler.sendMessage(msg);
            }

        } catch (IOException e) {
            Message msg=new Message();
            msg.what=0x02;
            mHandler.sendMessage(msg);
            Log.d(TAG,"TCP连接失败......0.0");
            e.printStackTrace();
        }

//            }
//        });
    }

    @SuppressLint("HandlerLeak")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clear_fault);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initWidght(); //关联
        mThreadPool = Executors.newCachedThreadPool();   // 初始化线程池

        mHandler = new Handler()
        {                    // 实例化主线程,用于更新接收过来的消息
            @SuppressLint("SetTextI18n")
            @Override
            public void handleMessage(android.os.Message msg)
            {
                Log.d(TAG, "button接收obj= "+msg.obj);
                Log.d(TAG, "button接收what= "+msg.what);
                switch(msg.what)
                {
                    case 0x01:

                        break;

                    case 0x02:
                        m_pDialog.cancel();     //关闭进度条对话框
                        btn_cx.setText("清除故障");
                        break;

                    case 0x03:
                        m_pDialog.cancel();     //关闭进度条对话框
                        btn_cx.setText("断开");
                        break;

                    case 0x04:
                        m_pDialog.cancel();     //关闭进度条对话框

                        AlertDialog dlg = new AlertDialog.Builder(clear_fault.this)
                                .setIcon(R.drawable.icon)
                                .setTitle("查询状态")
                                .setMessage("没有找到"+""+et_id.getText().toString()+""+"号机器！请重试")
                                .setPositiveButton("确定", null)
                                .create();
                        dlg.show();
                        break;
                }

            }
        };
        btn_Back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Intent intent = new Intent(clear_fault.this, MainActivity.class);
                startActivity(intent);
//                overridePendingTransition(R.anim.abc_slide_out_bottom, R.anim.abc_slide_in_bottom);
            }
        });
//        btn_qk.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//                if(bb==1)
//                {
//                    try {
//                        outputStream = socket.getOutputStream();
//                        outputStream.write(("aaaaaaaaaa\r\n").getBytes("utf-8"));	//WIFI状态开启
//                        outputStream.flush();
//                        Log.d(TAG, "aaaaaaaaaa");
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        });

        btn_cx.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View view)
            {

                Log.d(TAG,"输入的机器号为："+""+et_id.getText().toString()+"");

                if(bb==0)
                {
                    if(!et_id.getText().toString().equals("")){
                        final int id = Integer.parseInt(et_id.getText().toString());
                        if(id <= 50 && id >= 1) {
                            btn_cx.setText("连接中...");
                            ProgressShow();
                            new Thread() {
                                public void run() {

                                    Connect_Tcp(IP_HEAD + (id+100), 8080);

                                }
                            }.start();
                        }
                        else
                        {
                            AlertDialog dlg = new AlertDialog.Builder(clear_fault.this)
                                    .setIcon(R.drawable.icon)
                                    .setTitle("提示")
                                    .setMessage("请正确输入机器号！")
                                    .setPositiveButton("确定", null)
                                    .create();
                            dlg.show();
                        }

                    }
//                    if(et_id.getText().toString().equals(""))
                    else
                    {
                        AlertDialog dlg = new AlertDialog.Builder(clear_fault.this)
                                .setIcon(R.drawable.icon)
                                .setTitle("提示")
                                .setMessage("请输入机器号！")
                                .setPositiveButton("确定", null)
                                .create();
                        dlg.show();
                    }
                }
                else if(bb==1)
                {
                    new Thread()
                    {
                        public void run(){
                            try {
                                outputStream = socket.getOutputStream();
                                outputStream.write(("8888888888888888888888888888888\r\n").getBytes("utf-8"));	//WIFI状态关闭
                                outputStream.flush();
                                outputStream.close();
                                br.close();
                                socket.close();             //断开TCP
                                Message msg=new Message();
                                bb=0;
                                msg.what=0x02;
                                mHandler.sendMessage(msg);
                            } catch (IOException e){
                                e.printStackTrace();
                            }
                        }
                    }.start();

                }
            }


        });

    }
    @Override
    protected void onRestart() {
        super.onRestart();
//    mVideoView.start();
//
//    //监听视频播放完的代码
//    mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//        @Override
//        public void onCompletion(MediaPlayer mPlayer) {
//            // TODO Auto-generated method stub
//            mPlayer.start();
//            mPlayer.setLooping(true);           //循环播放
//        }
//    });
    }

    @SuppressLint("PrivateResource")
    @Override
    public void onBackPressed() {       //重写back按键
        super.onBackPressed();
        overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom);

        wi=0;
        if(bb==1)
        {
            new Thread()
            {
                public void run(){
                    try {
                        outputStream = socket.getOutputStream();
                        outputStream.write(("8888888888888888888888888888888\r\n").getBytes("utf-8"));		//WIFI状态关闭
                        outputStream.flush();
                        outputStream.close();
                        br.close();
                        socket.close();             //断开TCP
                        Message msg=new Message();
                        bb=0;
                        msg.what=0x02;
                        mHandler.sendMessage(msg);
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }
            }.start();

        }

        System.out.println("按下了back返回键，变量清零");
        return;
    }
}